package cn.com.infcn.spider.io.input.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

import cn.com.infcn.spider.io.input.Input;
import cn.com.infcn.spider.util.FileParser;

import com.alibaba.fastjson.JSONObject;

/**
 * 目录输入
 * 
 * @author ansj
 *
 */
public class directoryInput implements Input {

	private File base = null;

	private boolean isSkipHidden;

	public directoryInput(JSONObject job, String jobName) {
		base = new File(job.getString("path"));
		isSkipHidden = job.getBooleanValue("isSkipHidden");
	}

	@Override
	public List<?> all() {
		List<JSONObject> result = new ArrayList<JSONObject>();
		if (base.isDirectory()) {
			try {
				parseDir(base, result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			result.add(FileParser.parser(base)) ;
		}
		return result;
	}

	private void parseDir(File dir,final List<JSONObject> result) throws IOException {
		Files.walkFileTree(dir.toPath(), new FileVisitor<Path>() {

			//访问文件夹之前调用 
			@Override
			public FileVisitResult preVisitDirectory(Path dir,
					BasicFileAttributes attrs) throws IOException {

				//判断是否为隐藏目录，是否要跳过隐藏目录
				if (isSkipHidden && dir.toFile().isHidden()) {
					return FileVisitResult.SKIP_SUBTREE;
				}

				return FileVisitResult.CONTINUE;
			}

			// 访问文件调用
			@Override
			public FileVisitResult visitFile(Path file,
					BasicFileAttributes attrs) throws IOException {
				
				//判断是否为隐藏文件，是否要跳过隐藏文件
				if (isSkipHidden && file.toFile().isHidden()) {
					return FileVisitResult.SKIP_SUBTREE;
				}
				
				JSONObject obj = new JSONObject();
				obj.put("filename", file.getFileName().toString());
				obj.put("filePath", file.toFile().getAbsolutePath());
				result.add(obj);
				
				return FileVisitResult.CONTINUE;
			}

			// 访问文件失败时调用
			@Override
			public FileVisitResult visitFileFailed(Path file, IOException exc)
					throws IOException {
				// TODO Auto-generated method stub
				return FileVisitResult.CONTINUE;
			}

			// 访问文件夹之后调用
			@Override
			public FileVisitResult postVisitDirectory(Path dir, IOException exc)
					throws IOException {
				// TODO Auto-generated method stub
				return FileVisitResult.CONTINUE;
			}

		});
	}
}
